/**
 * Created by lixiaodi on 2019/06/10 0027.
 */
mini.parse();

var mailData = localStorage.getItem("mailData");
var mailInfo = JSON.parse(mailData);
console.log(mailInfo);
var userInfo = JSON.parse(localStorage.getItem("item"));
//得到编辑器
var ue = UE.getEditor('content',{
	//设置不自动增加高度
	scaleEnabled:true
});
var form = new mini.Form("form1");  		//得到页面上的表单
var sender = mini.getByName('send_people');	//发件人
var nowTime = mini.getByName('push_time');	//发件时间
var addressee = mini.getByName('user_id');	//收件人
var changeBtn = mini.get('changeBtn');		//选择按钮
var mailId;	//msg_info_id,信息id
var sendId;	//保存发件人id

//全局变量
var userName;		//发件人名称
var userId;			//发件人id
var replayType = '';		//类型
//原始信息显示字符串

//页面初始化
$(function (){
	//设置禁用
	ue.addListener('ready',function(){
		//这是编辑器溢出滚动
		ue.document.body.style.overflow = 'auto';
	});
	//ue.document.body.style.overflow = 'auto';
	if(mailData){
		switch (mailInfo.types){
			case '草稿发送':
				replayType = mailInfo.types;
				form.setData(mailInfo);
				//保存发件人id
				userId = mailInfo.send_people;
				//发件人赋值
				sender.setValue(mailInfo.send_peopleName);
				//收件人赋值
				addressee.setValue(mailInfo.userid);
		    	addressee.setText(mailInfo.userNames);
		    	//消息详情赋值
		    	ue.addListener('ready',function(){
		    		ue.setContent(mailInfo.msg_text);
		    	});
				//邮件id
				mailId = mailInfo.msg_info_id;
				break;
			case '回复':
				replayType = mailInfo.types;
				form.setData(mailInfo);
				//保存发件人id
				userId = mailInfo.userid;
				//发件人赋值
				sender.setValue(mailInfo.userNames);
				//收件人赋值
				addressee.setValue(mailInfo.send_people);
		    	addressee.setText(mailInfo.send_peopleName);
				//消息详情赋值
		    	ue.addListener('ready',function(){
		    		ue.setContent(mailInfo.old_msg);
		    	});
		    	mailId = '';
		    	//选择收件人禁用
		    	addressee.disable();
		    	changeBtn.disable();
				break;
			case '再次发送':
				form.setData(mailInfo);
				//保存发件人id
				userId = mailInfo.send_people;
				//发件人赋值
				sender.setValue(mailInfo.send_peopleName);
				//收件人赋值
				addressee.setValue(mailInfo.userid);
		    	addressee.setText(mailInfo.userNames);
		    	//消息详情赋值
		    	ue.addListener('ready',function(){
		    		ue.setContent(mailInfo.msg_text);
		    	})
				//邮件id
				//mailId = mailInfo.msg_send_id;
		    	mailId = '';
		    	break;
			case '转发':
				form.setData(mailInfo);
				//保存发件人id
				userId = mailInfo.send_people;
				//发件人赋值
				sender.setValue(mailInfo.send_peopleName);
		    	//消息详情赋值
		    	ue.addListener('ready',function(){
		    		ue.setContent(mailInfo.msg_text);
		    	})
		    	mailId = '';
		    	break;
		}
	}else{
		localStorage.removeItem("mailData");
		replayType = '新增';
		//新增
		userName = userInfo.uName;
		userId = userInfo.userId;
		//赋值
		sender.setValue(userName);
		mailId = '';
	}
	//获取当前时间
	var timestamp =Date.parse(new Date());
	//时间格式转换
	timestamp = formatDateSec(timestamp);
	//时间赋值
	nowTime.setValue(timestamp);
})
//选择收件人
function onChange(){
	mini.open({
        url: bootPATH + "../frame/frame1/pages/booking/Mail/persons.html",
        title: "选择人员列表",
        width: 700,
        height: 500,
        onload: function () {
            var iframe = this.getIFrameEl();
            var addData = addressee.getValue();
            var data = { addData: addData};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "save") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
				console.log(data);
                if (data.length > 0) {
              	  var ids = [];
              	  var names = [];
              	  for (var i = 0, l = data.length; i < l; i++) {
              		  var r = data[i];
              		  ids.push(r.PersonnelFiles_id);
              		  names.push(r.PersonnelFiles_OperatorName);
              	  }
              	  var id = ids.join(',');
              	  var nameText = names.join(',');
              	  addressee.setValue(id);
              	  addressee.setText(nameText);
                } else {
              	  mini.alert("请选中一条记录");
                }
            }

        }
    });
}
//保存(保存到草稿)
function onOk() {
	//校验
    form.validate();
    if (form.isValid() == false) return;
    //得到要保存的值
	var formData = form.getData();
	//编辑器中的值
	//var content = ue.getPlainTxt();
	var content = ue.getContent();
	
	var msgObj = {
			entityName:"MessageInfo",
			msg_info_id: mailId,
			msg_title: formData.msg_title,
			msg_text: content,
			appendix: '',
			send_people: userId,
			push_time: formData.push_time,
			user_id: formData.user_id,
			is_del: 0,
			ready_code: 0
	};
	var msgStr = JSON.stringify(msgObj);
	$.ajax({
		url:  ajaxUrl + '/msg/readyMsg.do',
		type: 'post',
		contentType : "application/json",
		data: msgStr,
		success : function(data){
			console.log(data);
			if(data.message == '1'){
				//清除缓存
				localStorage.removeItem('mailData');
				mini.alert(data.data + ',即将跳转草稿箱','系统提示',function(action){
					if(action == 'ok'){
						//获取当前选项卡
						var tab = parent.tabsEl.getActiveTab();
						//打开发件箱列表页
						var item = {
							//id: 'menuId480',
						    iconCls: "fa fa-desktop",
						    text: '草稿箱',
						    url: "../pages/booking/Mail/draftsBox.html"
						};
						//关闭当前选项卡并跳转
						parent.allTabs(tab,item);
					}
				});	
			}else{
				mini.alert(data.data);
			}
		},
		error: function(msg){
			alert("真的异常么");
			mini.alert('请求失败');
		}
	})
}

//保存并发送	
function saveAndRelease(){
	//校验
    form.validate();
    if (form.isValid() == false) return;
    //得到要保存的值
	var formData = form.getData();
	formData.userNames = addressee.getText();
	var contentTxt = ue.getPlainTxt();		//不带格式
	var content = ue.getContent();			//带格式
	//获取当前时间为发送时间
	var timestampSend =Date.parse(new Date());
	//时间格式转换
	timestampSend = formatDateSec(timestampSend);
	//oldmsg初始值
	var oldmsgStr = '';
	if(replayType == '回复'){
		var mOldMsg = mailInfo.old_msg;
		//拼接内容
		var contentArr = contentTxt.split('结束-');
		var len = contentArr.length;
		var contentEnd = contentArr[len-1].replace(/[\-]/g,'');
		content = contentEnd;
		oldmsgStr = mOldMsg + strChange(formData,contentEnd);
	//新增
	}else{
		//将发送的信息拼接为原始信息
		oldmsgStr = strChange(formData,contentTxt);
	}
	
	var msgObj = {
			entityName:"MessageInfo",
			msg_info_id: mailId,
			msg_text: content,
			msg_title: formData.msg_title,
			appendix: '',
			is_del: 0,
			old_msg: oldmsgStr,
			send_people: userId,
			push_time: formData.push_time,
			user_id: formData.user_id,
			ready_code: 1
	};
	var msgStr = JSON.stringify(msgObj);

	$.ajax({
		url: ajaxUrl + "/msg/createMsg.do",
		type: 'post',
		contentType : "application/json",
		data: msgStr,
		success : function(data){
			if(data.status == 200){
				//清除缓存
				localStorage.removeItem('mailData');
				var n = localStorage.getItem('mailData');
				if(n){
					localStorage.removeItem('mailData');
				}else{
					mini.alert(data.data + ',即将跳转发件箱','系统提示',function(action){
						if(action == 'ok'){
							//获取当前选项卡
							var tab = parent.tabsEl.getActiveTab();
							var item = {
									//id: 'menuId480',
								    iconCls: "fa fa-desktop",
								    text: '发件箱',
								    url: "../pages/booking/Mail/outbox.html"
							};
							//关闭当前选项卡
							parent.allTabs(tab,item);
						}
					});	
				}
				
			}else{
				mini.alert(data.data);
			}
		},
		error   : function(msg){
			mini.alert('失败');
		}
	})
}
//字符串赋值拼接
function strChange(formData,contentTxt){
	var oldmsgStr = 
		`<p>
		    <span style="font-size: 10px;">----------------原始信息开始------------------</span>
		</p>
		<p>
		    <span style="font-size: 10px;">发件人：${formData.send_people}；</span>
		</p>
		<p>
		    <span style="font-size: 10px;">发件时间：${formData.push_time}；</span>
		</p>
		<p>
		    <span style="font-size: 10px;">收件人：${formData.userNames}；</span>
		</p>
		<p>
		    <span style="font-size: 10px;">信息主题：${formData.msg_title}；</span>
		</p>
		<p>
		    <span style="font-size: 10px;">信息内容：${contentTxt}；</span>
		</p>
		<p>
		    <span style="font-size: 10px;">----------------原始信息结束------------------</span>
		</p>`;
	return oldmsgStr;
}
//校验模块必输
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}
//提示信息
function showTips(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}
//附件下载
//var sourceUrl = $(this).attr("href");
//var contentDown = ue.getContent();	
function xiazai(){
	//var sourceUrl = 'http://localhost:8080/bpm/ueditor/jsp/upload/file/20190715/1563156817957023269.xlsx';
	//var sourceUrl = '/Users/xiebingli/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp3/wtpwebapps/bpm_booking/ueditor/jsp/upload/file/20190715/1563156407628099691.xlsx';
	//var sourceUrl = 'http://localhost:8080/bpm/ueditor/jsp/upload/file/20190715/1563156817957023269.xlsx';
	var sourceUrl = 'D:/name-space2/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/bpm_booking/ueditor/jsp/upload/file/20190716/1563240387700039322.xml';
	$.ajax({
		url: ajaxUrl + "/FileController/download.do",
		type:'POST',
		data:{
			filePath: sourceUrl
		},
		//contentType : "application/json",
		success: function (data){
			console.log(data);
		},
		error: function (data){
			console.log(data);
		}
	})
}
//获取当前选项卡
//var tabClose = parent.tabsEl.getActiveTab();
//parent.articleTab(tabClose);
////设置编辑器只读
//function setDisabled() {
//    ue.setDisabled('fullscreen');
//};
////取消只读
//function setEnabled() {
//    ue.setEnabled();
//}